<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>商品管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/layui-cms-public.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
      <!--搜索开始-->
      <fieldset class="layui-elem-field layuimini-search">
        <legend>搜索信息</legend>
        <div style="margin: 10px 10px 10px 10px">
          <form class="layui-form layui-form-pane" action="" id="searchFrm">
            <div class="layui-form-item">
              <div class="layui-inline">
                  <label class="layui-form-label">供应商</label>
                  <div class="layui-input-inline">
                      <select name="providerId" class="providerSel">
                        <option value ="">请选择供应商</option>
                      </select>
                  </div>
              </div>
              <div class="layui-inline">
                  <label class="layui-form-label">商品名称</label>
                  <div class="layui-input-inline">
                    <input type="text" name="goodsName" autocomplete="off" class="layui-input">
                  </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">生产批号</label>
                <div class="layui-input-inline">
                  <input type="text" name="batchNo"   autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">批准文号</label>
                <div class="layui-input-inline">
                  <input type="text" name="promitCode" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">商品规格</label>
                <div class="layui-input-inline">
                  <input type="text" name="spec"   autocomplete="off" class="layui-input">
                </div>
              </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-block" style="text-align: center;">
                <a class="layui-btn " lay-submit=""  lay-filter="data-search-btn"><label class="layui-icon layui-icon-search"></label>搜索</a>
                <a class="layui-btn layui-btn-warm" onclick="javascript:$('#searchFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
              </div>
            </div>
          </form>
        </div>
      </fieldset>
      <!--搜索结束-->

      <script type="text/html" id="enableTpl">
        <input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="enableSwitch" {{ d.enable == 1 ? 'checked' : '' }}>
      </script>

      <script type="text/html" id="toolBar">
        <div class="layui-btn-group">
          <a class="layui-btn layui-btn-sm data-count-add" lay-event="add">添加</a>
          <a class="layui-btn layui-btn-sm data-count-delete" lay-event="delete">删除</a>
        </div>
      </script>
      <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

      <script type="text/html" id="tableBar">
        <a class="layui-btn layui-btn-xs layui-btn-warm data-count-update" lay-event="update">修改</a>
      </script>

      <!--添加和修改的弹出层开始-->
      <div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
        <form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
            <div class="layui-col-md12 layui-col-xs12">
                <div class="layui-row layui-col-space10">
                  <div class="layui-col-md9 layui-col-xs7">
                    <div class="layui-form-item magt3">
                      <label class="layui-form-label">供应商</label>
                      <div class="layui-input-block">
                      <select name="providerId" class="providerSel">
                        <option value ="">请选择供应商</option>
                      </select>
                      </div>
                    </div>
                  <div class="layui-form-item magt3">
                    <label class="layui-form-label">商品名称</label>
                    <div class="layui-input-block">
                      <input type="hidden" name="id" />
                      <input type="text" name="goodsName" class="layui-input" lay-verify="required" placeholder="请输入商品名称">
                    </div>
                  </div>
                  <div class="layui-form-item magt3">
                    <label class="layui-form-label">商品描述</label>
                    <div class="layui-input-block">
                      <input type="text" name="description"  class="layui-input" lay-verify="required" placeholder="请输入商品描述">
                    </div>
                  </div>
                  </div>
                  <div class="layui-col-md3 layui-col-xs5">
                    <div class="layui-upload-list thumbBox mag0 magt3">
                    <input type="hidden" name="goodsImg" id="goodsimg" />
                    <img class="layui-upload-img thumbImg">
                    </div>
                  </div>
                </div>
                <div class="layui-form-item magb0">
                  <div class="layui-inline">
                  <label class="layui-form-label">产地</label>
                  <div class="layui-input-inline">
                    <input type="text" name="producePlace" class="layui-input " lay-verify="required" placeholder="请输入商品产地">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">包装</label>
                  <div class="layui-input-inline">
                    <input type="text" name="goodsPackage" class="layui-input " lay-verify="required" placeholder="请输入商品包装">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">规格</label>
                  <div class="layui-input-inline">
                    <input type="text" name="spec" class="layui-input " lay-verify="required" placeholder="请输入商品规格">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">生产批号</label>
                  <div class="layui-input-inline">
                    <input type="text" name="batchNo" class="layui-input " lay-verify="required" placeholder="请输入商品生产批号">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">批准文号</label>
                  <div class="layui-input-inline">
                    <input type="text" name="promitCode" class="layui-input " lay-verify="required" placeholder="请输入商品批准文号">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">销售价格</label>
                  <div class="layui-input-inline">
                    <input type="text" name="price" class="layui-input " lay-verify="required" placeholder="请输入商品价格">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">库存量</label>
                  <div class="layui-input-inline">
                    <input type="text" name="number" class="layui-input " lay-verify="required" placeholder="请输入商品库存量">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">预警值</label>
                  <div class="layui-input-inline">
                    <input type="text" name="dangerNum" class="layui-input " lay-verify="required" placeholder="请输入商品库存预警值">
                  </div>
                </div>
                </div>
              </div>
            <div class="layui-form-item">
              <div class="layui-input-block" style="text-align: center;">
                <a class="layui-btn " lay-submit=""  lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
                <a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
              </div>
            </div>
        </form>
      </div>
      <!--添加和修改的弹出层结束-->

    </div>
</div>

<script src="/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/lib/common/jquery.cookie.min.js" charset="utf-8"></script>
<script src="/lib/common/common.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','upload'], function () {
      var $ = layui.jquery,
          form = layui.form,
          table = layui.table;
      var upload=layui.upload;

      // 加载查询条件里面的供应商的下拉列表
      $.get(api+"/provider/getAllEnableProvider",function(res){
        var search_providerid=$(".providerSel");
        var html="<option value =''>请选择供应商</option>";
        var data=res.data;
        $.each(data,function(index,item){
          html+="<option value ="+item.id+">"+item.providerName+"</option>"
        });
        search_providerid.html(html);
        form.render("select");
      });
		
      var tableIns = table.render({
          elem: '#currentTableId',
          url: api + '/goods/getByPage',
          method: 'post',
          contentType: "application/json; charset=utf-8",
          toolbar:"#toolBar",
          cellMinWidth: true,
          parseData: function(res){ //res 即为原始返回的数据
            return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": res.data.total, //解析数据长度
              "data": res.data.records //解析数据列表
            };
          },
          response:{ // 必须配置，否则不加载数据
            statusName:'code', //规定返回的状态码字段为code
            statusCode:200 //规定成功的状态码味200
          },
          done: function(res, curr, count){
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            // console.log(res);
            //得到当前页码
            // console.log(curr); 
            //得到数据总量
            // console.log(count);
          },
          cols: [[
            {type: "checkbox", width: 50, fixed: "left"},
            {type: "numbers", width: 40, title: '序号', fixed: "left"},
            {field: 'id', title: 'ID', hide: true},
            {field: 'goodsName', minWidth: 100, title: '商品名称'},
            {field: 'providerName', title: '供应商'},
            {field: 'goodsImg',  title: '商品预览', align: "center",width:120,templet:function(d){
              var img = d.goodsImg? d.goodsImg : "/images/noimage.png"
              return "<img width=30 height=30 src='"+img+"' />"
            }},
            {field: 'producePlace', title: '产地'},
            {field: 'spec', title: '规格'},
            {field: 'goodsPackage', title: '包装'},
            {field: 'batchNo',  title: '生产批号'},
            {field: 'promitCode', title: '批准文号'},
            {field: 'price', title: '价格'},
            {field: 'number', title: '数量'},
            {field: 'dangerNum', title: '预警值'},
            {field: 'enable',  title: '是否启用', align: "center",width: 120,templet:'#enableTpl'},
            {title: '操作', templet: '#tableBar', fixed: "right", align: "center"}
          ]],
          limits: [10, 15, 20, 25, 5],
          limit: 15,
          page: true
      });

      // 监听搜索操作
      form.on('submit(data-search-btn)', function (data) {
          //执行搜索重载
          table.reload('currentTableId', {
            page: {
              curr: 1
            },
            where: {
              queryParams: {
                "providerId" : data.field.providerId,
                "goodsName": data.field.goodsName,
                "batchNo": data.field.batchNo,
                "promitCode": data.field.promitCode,
                "spec": data.field.spec
              }
            },
            async: true
          }, 'data');

          return false;
      });

      var formState = FORM_ADD;
      //提交数据
      form.on("submit(doSubmit)",function(data){
        $.ajax({
          url: url,
          method: formState === FORM_ADD ? "post" : "put",
          async: true,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: JSON.stringify(data.field),
          success:function(res){
            layer.msg(res.msg);
            if(res.code == SUCCESS_CODE) {
              tableIns.reload();
            }
          },
          error:function(){
            layer.msg("操作失败");
          }
        });
        layer.close(mainIndex);
        return false;
      });
 
      //监听表头的事件
      table.on('toolbar(currentTableFilter)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
          case 'delete':
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if(data.length > 0) {
                layer.confirm('真的删除么', function (index) {
                  var arr = [];
                  //遍历
                  data.forEach(function(item){
                    arr.push(item.id)
                  });
                  $.ajax({
                    url: api + "/goods/deleteByIds",
                    method: "delete",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(arr),
                    success:function(res){
                      layer.msg(res.msg);
                      tableIns.reload();
                    },
                    error:function(){
                      layer.msg("删除失败");
                    }
                  });
                  layer.close(index);
              });
            }
          break;
          case 'add':
            openAddGoods();
          break;
        };
      });

      //监听行数据的事件
      table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'update'){
				  openUpdateGoods(data);
		    }
      });

      //打开添加商品的弹层
      var mainIndex;
      var url;  //动态的url
      function openAddGoods(){
        formState = FORM_ADD;
        mainIndex=layer.open({
          type:1,
          title:'添加商品',
          content:$("#addOrUpdateDiv"),
          area:['800px','450px'],
          success:function(index){
            url=api + "/goods/addGoods";
            //重置表单
            $("#dataFrm")[0].reset();
            //移除src属性
            $('.thumbImg').attr('src','');
            //清除图片隐藏域的值
            $("#goodsimg").val('');
          }
        });	
      };

      function openUpdateGoods(data) {
        formState = FORM_UPDATE;
        mainIndex=layer.open({
          type:1,
          title:'修改商品',
          content:$("#addOrUpdateDiv"),
          area:['800px','600px'],
          success:function(index){
            url=api + "/goods/updateGoods";
            //装载数据表格
            form.val("dataFrm",data);
            var img = data.goodsImg? data.goodsImg : "/images/noimage.png"
            $('.thumbImg').attr('src', img);
          }
        });	
      };

      //监听启用操作
      form.on('switch(enableSwitch)', function(obj){
        let tmp = obj.elem.checked? "enable" : "disable";
        console.log(tmp);
        console.log(api);
        console.log(api + "/goods/" + tmp);
        $.ajax({
          url: api + "/goods/" + tmp,
          method: "put",
          async: true,
          data: {"id" : this.value},
          success:function(res){
            layer.msg(res.msg);
            if(res.code != SUCCESS_CODE)// 修改失败时，刷新界面状态为最新状态
              tableIns.reload();
          },
          error:function(){
            layer.msg("操作失败");
          }
        });
      });

      //上传缩略图
      upload.render({
        elem: '.thumbBox',
        url: api+'/upload/image',
        field: "file", //设定文件域的字段名
        acceptMime: 'image/*',
        done: function(res, index, upload){
          $('.thumbImg').attr('src', res.data);
          $('.thumbBox').css("background","#fff");
          $("#goodsimg").val(res.data);
        }
      });
    });
</script>
<script>

</script>

</body>
</html>